﻿using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 协议管理器
/// </summary>
public class ProtocolMgr : UnitySingleton<ProtocolMgr>
{
    private Dictionary<int, Action<byte[]>> protocolHandlers = new Dictionary<int, Action<byte[]>>();

    /// <summary>
    /// 注册协议处理器
    /// </summary>
    public void RegisterHandler(int protocolId, Action<byte[]> handler)
    {
        if (protocolHandlers.ContainsKey(protocolId))
        {
            protocolHandlers[protocolId] += handler;
        }
        else
        {
            protocolHandlers.Add(protocolId, handler);
        }
    }

    /// <summary>
    /// 注销协议处理器
    /// </summary>
    public void UnregisterHandler(int protocolId, Action<byte[]> handler)
    {
        if (protocolHandlers.TryGetValue(protocolId, out Action<byte[]> existingHandler))
        {
            existingHandler -= handler;
            if (existingHandler == null)
            {
                protocolHandlers.Remove(protocolId);
            }
            else
            {
                protocolHandlers[protocolId] = existingHandler;
            }
        }
    }

    /// <summary>
    /// 处理接收到的协议数据
    /// </summary>
    public void ProcessProtocolData(int protocolId, byte[] data)
    {
        if (protocolHandlers.TryGetValue(protocolId, out Action<byte[]> handler))
        {
            handler?.Invoke(data);
        }
        else
        {
            LoggerMgr.Instance.Log($"No handler registered for protocol ID: {protocolId}", LoggerMgr.LogLevel.Warning);
        }
    }
}